﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using ProjectEuler.Linq;

namespace ProjectEuler.Problems
{
    [EulerProblem(23, 4179871)]
    [Description("Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.")]
    internal sealed class Problem023 : EulerProblem
    {
        private readonly List<Int32> _abundantNumbers = new List<Int32>();
        private readonly Func<Int32, Boolean> _isAbundant;

        private Int32 _lastNumberTested;

        public Problem023()
        {
            _isAbundant = Functional.Memoize((Int32 n) =>
            {
                if (n.IsAbundant())
                {
                    _abundantNumbers.Add(n);
                    return true;
                }

                return false;
            });
        }

        public override Object Solve()
        {
            return
                (1).To(23).Sum() +
                (25).To(28123).Sum(n => IsSumOfAbundantNumbers(n) ? 0 : n);
        }

        private Boolean IsSumOfAbundantNumbers(Int32 n)
        {
            var nhalf = n / 2;
            FindAbundantNumbersUpTo(n);

            return _abundantNumbers
                .TakeWhile(x => x <= nhalf)
                .Any(x => _isAbundant(n - x));
        }

        private void FindAbundantNumbersUpTo(Int32 max)
        {
            while (_lastNumberTested < max)
            {
                _lastNumberTested++;
                _isAbundant(_lastNumberTested);
            }
        }
    }
}
